package top.rainbowecho.notify.domain.model.email;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.thymeleaf.TemplateEngine;
import top.rainbowecho.common.mq.mo.MailMeta;
import top.rainbowecho.notify.domain.model.email.db.repository.TemplateMapper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * 发送邮件的最简单的逻辑，可以发送带文本的HTML格式的邮件。邮件发送速度在3-4s一封
 *
 * @author rainbow
 * @since 2019/11/28 13:32
 */
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public abstract class Mail {
    private String from;

    private JavaMailSender sender;

    private TemplateEngine templateEngine;

    private TemplateMapper templateMapper;

    /**
     * 根据模板文件或者是输入的邮件内容生成HTML格式邮件
     *
     * @param info 输入的邮件内容
     * @return 生成的邮件
     * @throws MessagingException 生成失败异常
     */
    public MimeMessage generateHtmlMail(MailMeta info) throws MessagingException, IOException {
        MimeMessage mail = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mail, true);
        helper.setFrom(from);
        helper.setSentDate(new Date());
        helper.setTo(info.getTo().toArray(new String[0]));
        if (StringUtils.isNotBlank(info.getSubject())) {
            helper.setSubject(info.getSubject());
        }
        if (StringUtils.isNotEmpty(info.getContent())) {
            helper.setText(info.getContent(), true);
        }

        return mail;
    }

    /**
     * 发送邮件
     *
     * @param mail 生成的邮件
     */
    public void send(MimeMessage mail) {
        sender.send(mail);
    }
}
